#include "uart.h"

namespace igslib
{
    RS232::RS232()
    {
        port = -1;
    }
    parity_mode RS232::map_parity_mode(ParityMode value)
    {
        parity_mode rtn = none;
        if (value == pm_odd) rtn = odd;
        if (value == pm_even) rtn = even;
        return rtn;
    }
    data_bits RS232::map_data_bits(DataBits value)
    {
        data_bits rtn = db8;
        if (value == data_5bits) rtn = db5;
        if (value == data_6bits) rtn = db6;
        if (value == data_7bits) rtn = db7;
        if (value == data_9bits) rtn = db9;
        return rtn;
    }
    stop_bits RS232::map_stop_bits(StopBits value)
    {
        stop_bits rtn = sb1;
        if (value == stop_2bits) rtn = sb2;
        return rtn;
    }
    bool RS232::Open(DeviceNumber number)
    {
        bool rtn = true;
        port = static_cast<int>(number);
        RS232_SetAttributes(
                map_parity_mode(pm),
                map_data_bits(db),
                map_stop_bits(sb)
        );
        int odr = RS232_OpenComport(port,GetBaudRate()); // open device result
        if (odr) rtn = false;
        return rtn;
    }
    void RS232::FlushBuffer()
    {
        RS232_FlushBuffer(port);
    }
    void RS232::Close()
    {
        RS232_CloseComport(port);
    }
    int RS232::Send(char* addr,int length)
    {
        return RS232_SendBuf(port,(unsigned char*)addr,length);
    }
    int RS232::Receive(char* addr,int length)
    {
        return RS232_PollComport(port,(unsigned char*)addr,length);
    }
};
